import React, { useEffect, useState } from "react";
import {
  Card,
  Form,
  Button,
  Input,
  Select,
  Table,
  Row,
  Col,
  message,
} from "antd";
import { SearchOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
// 引入请求
import {
  gethospitalListRequest,
  getProvinceRequest,
  getCityOrAreaRequest,
  changeStatusRequest,
} from "@api/hospital/hospitalList";
// 引入类型
import {
  hospitalListContentType,
  hosListItemType,
  hospitalListsearchParamsType,
  getProvinceReturnRequestType,
} from "@api/hospital/model/hospitalListType";

export default function HospitalList() {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const [isLoading, setIsLoading] = useState(false);
  // 设置当前页码的状态
  const [page, setPage] = useState(1);
  // 设置一页拥有的数据条数的状态
  const [limit, setLimit] = useState(3);
  // 设置总数据条数的数量
  const [total, setTotal] = useState(0);
  // 设置表单的状态
  const [seachParams, setSeachParams] = useState({});
  // 设置医院列表的状态
  const [hosList, setHosList] = useState<hospitalListContentType>([]);
  // 设置省份的state
  const [province, setProvince] = useState<getProvinceReturnRequestType>([]);
  // 设置市的state
  const [city, setCity] = useState<getProvinceReturnRequestType>([]);
  // 设置区的state
  const [area, setArea] = useState<getProvinceReturnRequestType>([]);
  // 设置医院等级的state
  const [hostype, setHosType] = useState<getProvinceReturnRequestType>([]);
  //重新渲染页面
  const [render, setRebder] = useState(true);

  // 请求医院列表
  useEffect(() => {
    setIsLoading(true);
    const gethospitalList = async () => {
      const re = await gethospitalListRequest(page, limit, seachParams);
      // console.log(re);
      setHosList(re.content);
      setIsLoading(false);
      setTotal(re.totalElements);
    };
    gethospitalList();
  }, [page, limit, seachParams, render]);

  // 请求省份
  useEffect(() => {
    const getProvince = async () => {
      const result = await getProvinceRequest();
      setProvince(result);
    };
    getProvince();
  }, []);

  // 请求医院等级
  useEffect(() => {
    const getHosType = async () => {
      const result = await getCityOrAreaRequest("10000");
      // console.log(result);

      setHosType(result);
    };
    getHosType();
  }, []);

  // 设置一个点击事件 改变上下线的状态
  const changeStatushandle = (id: string, status: 0 | 1) => {
    return async () => {
      await changeStatusRequest(id, status);
      message.success("改变status状态成功");
      setRebder(!render);
    };
  };

  const tableData = hosList;
  const columns = [
    {
      title: "序号",
      width: 70,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      render(_: any, data: hosListItemType) {
        return (
          <img
            width={"100px"}
            src={`data:image/jpeg;base64,${data.logoData}`}
          />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      dataIndex: "hostypeString",
      render(_: any, data: hosListItemType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      dataIndex: "fullAddress",
      render(_: any, data: hosListItemType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      render(_: any, data: hosListItemType) {
        return data.status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 245,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any, data: hosListItemType) {
        console.log(data, "data");
        const { id, status,hoscode } = data;
        return (
          <div>
            <Button
              type="primary"
              style={{ marginRight: 10 }}
              onClick={() => {
                navigate(`/syt/hospital/hospitaldetail/${data.id}`);
              }}
            >
              查看
            </Button>
            <Button type="primary" onClick={()=>{navigate(`/syt/hospital/hospitalSchedule/${hoscode}`)}} style={{ marginRight: 10 }}>
              排班
            </Button>
            <Button type="primary" onClick={changeStatushandle(id, status===0?1:0)}>
              {status === 0 ? "上线" : "下线"}
            </Button>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card>
        <Form
          name="basic"
          onFinish={async (data: hospitalListsearchParamsType) => {
            setSeachParams(data);
          }}
          form={form}
          // wrapperCol={{ span: 30 }}
        >
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="provinceCode">
                <Select
                  placeholder="请输入省份"
                  onChange={async (value: string) => {
                    const re = await getCityOrAreaRequest(value);
                    setCity(re);
                    form.setFieldsValue({ cityCode: null, districtCode: null });
                  }}
                  allowClear
                >
                  {province.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请输入市"
                  onChange={async (value: string) => {
                    const re = await getCityOrAreaRequest(value);
                    setArea(re);
                    form.setFieldsValue({ districtCode: null });
                  }}
                  allowClear
                >
                  {city.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="districtCode">
                <Select placeholder="请输入县/区" allowClear>
                  {area.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型" allowClear>
                  {hostype.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Select.Option value="male">上线</Select.Option>
                  <Select.Option value="female">下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>

            <Col span={2} style={{ marginLeft: "-18px" }}>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<SearchOutlined />}
                >
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="default" htmlType="reset">
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Table
          columns={columns}
          dataSource={tableData}
          scroll={{ x: 1500 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            onChange(page, pageSize) {
              return setPage(page), setLimit(pageSize);
            },
            showTotal(total) {
              return `总共有${total}条数据`;
            },
          }}
        />
      </Card>
    </div>
  );
}
